<template>
    <div :class='$style.addForm'>
        <XFormBox>
            <el-form ref='formRef' :rules='rules' :model='formData' size='small' label-position='top'>
                <el-form-item label='商户名称' prop='merchantName'>
                    <el-input type='text' clearable show-word-limit :maxlength='rules.merchantName[1].max' v-model='formData.merchantName' />
                </el-form-item>
                <template v-if='merchantId == 0'>
                    <el-form-item label='登录账号' prop='account'>
                        <el-input type='text' clearable show-word-limit :maxlength='rules.account[1].max' v-model='formData.account' />
                    </el-form-item>
                    <el-form-item label='登录密码' prop='password'>
                        <el-input type='password' clearable :maxlength='rules.password[1].max' v-model='formData.password' />
                    </el-form-item>
                </template>
                <template v-if='$store.getters.isMerchant'>
                    <el-form-item label='分成比例' prop='profitRate'>
                        <el-input type='text' clearable v-model.number='formData.profitRate'>
                            <template #append>%</template>
                        </el-input>
                    </el-form-item>
                </template>
                <template v-if='$store.getters.isPlatform'>
                    <el-form-item label='提现费率' prop='withdrawalRate'>
                        <el-input type='text' clearable v-model.number='formData.withdrawalRate'>
                            <template #append>%</template>
                        </el-input>
                    </el-form-item>
                </template>
                <el-form-item label='权限角色'>
                    <el-select class='w-100' multiple v-model='formData.roles'>
                        <el-option v-for='role in rolesOptions' :key='role.id' :value='role.id' :label='role.name'></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label='联系人'>
                    <el-input type='text' maxlength='15' show-word-limit clearable v-model='formData.contact' />
                </el-form-item>
                <el-form-item label='联系电话'>
                    <el-input type='text' maxlength='20' show-word-limit clearable v-model='formData.phone' />
                </el-form-item>
                <el-form-item label='所在地区'>
                    <XLazyloadCascader class='w-100' valueField='id' labelField='name' v-model='districts' :level='3' :loadFunc='getDistrictByParentIdApi' @change='selectDictrict' />
                </el-form-item>
                <el-form-item label='详细地址'>
                    <el-input type='text' maxlength='50' show-word-limit clearable v-model='formData.address' />
                </el-form-item>
                <el-form-item label='备注'>
                    <el-input type='textarea' :rows='3' maxlength='100' show-word-limit clearable v-model='formData.remark' />
                </el-form-item>
                <div class='text-center m-t-20'>
                    <XRequestButton :click='submit'>
                        <el-button type='primary'>确 定</el-button>
                    </XRequestButton>
                </div>
            </el-form>
        </XFormBox>
    </div>
</template>

<script lang='ts' setup>
    import { ElMessage } from 'element-plus'
    import { getDistrictByParentIdApi } from '../../../api/district'
    import { addMerchantApi, editMerchantApi, getMerchantEditDataApi } from '../../../api/merchant'
    import { filterEmpty } from '../../../utils'
    import { reactive, ref } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    import { getSelectedRolesApi } from '../../../api/permissionRole'
import { useStore } from 'vuex'

    const $store = useStore()

    let merchantId = ref(0)
    const rolesOptions = reactive([])
    const formData = reactive<any>({
        merchantName : '',
        account : '',
        password : '',
        profitRate : '',
        withdrawalRate : null,
        roles : [],
        contact : '',
        phone : '',
        provinceId : '',
        cityId : '',
        districtId : '',
        address : '',
        remark : ''
    })
    let districts = reactive<string[]>([])
    const rules = reactive({
        merchantName : [
            {
                required : true,
                message : '请输入商户名称'
            },
            {
                min : 2,
                max : 15,
                message: '商户名称长度在2-15之间',
            }
        ],
        account : [
            {
                required : true,
                message : '请输入登录账号'
            },
            {
                min : 6,
                max : 20,
                message: '登录账号长度在6-20之间',
            }
        ],

        password : [
            {
                required : true,
                message : '请输入登录密码'
            },
            {
                min : 6,
                max : 20,
                message: '登录密码长度在6-20之间',
            }
        ],

        profitRate : [
            {
                required : true,
                message : '请输入分成比例'
            },
            {
                type : 'number',
                min : 0,
                max : 100,
                message : '分成比例在0-100之间'
            }
        ],

        withdrawalRate : [
            {
                required : true,
                message : '请输入提现费率'
            },
            {
                type : 'number',
                min : 0,
                max : 100,
                message : '提现费率在0-100之间'
            }
        ]
    })

    const formRef = ref()
    const route = useRoute()
    const router = useRouter()

    function selectDictrict(e) {
        formData.provinceId = e[0]
        formData.cityId = e[1]
        formData.districtId = e[2]
    }

    async function submit() {
        try {
            await formRef.value.validate()
            const data = {...formData}
            if(!merchantId.value) { //新增
                filterEmpty(data)
                const res = await addMerchantApi(data)
                if(res.success) {
                    ElMessage.success!('增加成功')
                }else {
                    ElMessage.error!(res.msg)
                    return
                }
            }else {
                const res = await editMerchantApi(merchantId.value, data)
                if(res.success) {
                    ElMessage.success!('编辑成功')
                }else {
                    ElMessage.error!(res.msg)
                    return
                }
            }

            router.go(-1)
            
        } catch (error) {
            console.log(error)
        }
    }

    async function init() {
        getSelectedRolesApi().then(roles => {
            if(roles) {
                rolesOptions.push(...roles)
            }
        })
        if(route.params.merchantId) {
            merchantId.value = Number(route.params.merchantId)
            const data:typeof formData = await getMerchantEditDataApi(merchantId.value)
            
            if(!data) {
                ElMessage.error!('数据不存在')
                useRouter().go(-1)
            }else {
                for(let k in formData) {
                    if(k in data) {
                        if(k == 'profitRate' || k == 'withdrawalRate') {
                            data[k] = Number(data[k])
                        }
                        formData[k] = data[k]
                    }
                }

                if(formData.provinceId > 0) {
                    districts.push(formData.provinceId)
                }
                if(formData.cityId > 0) {
                    districts.push(formData.cityId)
                }
                if(formData.districtId > 0) {
                    districts.push(formData.districtId)
                }
            }
        }
    }

    init()

    

</script>

<style scoped lang='scss' module>
    .addForm{
        margin: auto;
        max-width: 600px;
    }
</style>